import React from "react";
import {
  useReactTable,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  flexRender,
} from "@tanstack/react-table";
import {
  Table,
  TableHeader,
  TableRow,
  TableCell,
  TableBody,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";

// 假设的数据类型
interface RowData {
  id: number;
  name: string;
  age: number;
}

const SelectableTable: React.FC = () => {
  const [data, setData] = React.useState<RowData[]>([
    { id: 1, name: "Alice", age: 30 },
    { id: 2, name: "Bob", age: 25 },
    { id: 3, name: "Charlie", age: 35 },
  ]);
  const [selectedRowData, setSelectedRowData] = React.useState<RowData | null>(
    null
  );

  const columns = [
    {
      id: "select",
      header: ({ table }: any) => (
        <input
          type="checkbox"
          checked={table.getIsAllRowsSelected()}
          onChange={(e) => table.toggleAllRowsSelected(e.target.checked)}
        />
      ),
      cell: ({ row }: any) => (
        <input
          type="checkbox"
          checked={row.getIsSelected()}
          onChange={(e) => row.toggleSelected(e.target.checked)}
        />
      ),
    },
    {
      accessorKey: "name",
      header: () => <div>Name</div>,
    },
    {
      accessorKey: "age",
      header: () => <div>Age</div>,
    },
  ];

  const table = useReactTable({
    data,
    columns,
    state: {
      rowSelection: {},
    },
    onStateChange: (state) => {
      if ("rowSelection" in state) {
        const selectedRowIds = Object.keys(state.rowSelection);
        if (selectedRowIds.length > 0) {
          const firstSelectedRow = data.find((row) =>
            selectedRowIds.includes(`${row.id}`)
          );
          setSelectedRowData(firstSelectedRow || null);
        } else {
          setSelectedRowData(null);
        }
      }
    },
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    enableRowSelection: true,
    debugTable: true,
    debugHeaders: true,
    debugColumns: false,
  });

  return (
    <div className="p-4">
      <div className="w-full">
        <Table>
          <TableHeader>
            <TableRow>
              {table.getHeaderGroups().map((headerGroup) => (
                <TableRow key={headerGroup.id}>
                  {headerGroup.headers.map((header) => (
                    <TableCell key={header.id}>
                      {flexRender(
                        header.column.columnDef.header,
                        header.getContext()
                      )}
                    </TableCell>
                  ))}
                </TableRow>
              ))}
            </TableRow>
          </TableHeader>
          <TableBody>
            {table.getRowModel().rows.map((row) => (
              <TableRow
                key={row.id}
                data-state={row.getIsSelected() && "selected"}
              >
                {row.getVisibleCells().map((cell) => (
                  <TableCell key={cell.id}>
                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                  </TableCell>
                ))}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
      <Button onClick={() => console.log("Selected Row:", selectedRowData)}>
        Submit
      </Button>
    </div>
  );
};

export default SelectableTable;
